from scapy.all import *

import socket

MAX_PORT = 65535
SYN_FLAG = 2
SYN_ACK_FLAG = 18
TIMEOUT = 0.1

def syn_scan(host, update):
	ip = socket.gethostbyname(host)
	open_ports = []
	filtered_ports = []
	
	#Envia de a 1000 paquetes por vez, es una optimizacion.
	#No se puede enviar todos los 65k paqetes porque scapy se satura
	from_p = 0
	to_p = 1000
	
	for i in range(65):
		update(i*1000)
				
		if i == 65:
			to_p = MAX_PORT
	
		pak = IP(dst=ip) / TCP(flags = SYN_FLAG, dport = (from_p, to_p))
		ans, un = sr(pak, timeout=TIMEOUT, verbose = 0)
		
		if un != None:
			for u in un:
				filtered_ports.append(u['TCP'].dport)
		
		for an in ans:
			if an[1]['TCP'].flags == SYN_ACK_FLAG:
				open_ports.append(an[0]['TCP'].dport)
				
		from_p += 1000
		to_p += 1000
	
	return (open_ports, filtered_ports)
	
	
def connect_scan(host, update):
	open_ports = []
	ip = socket.gethostbyname(host)

	for port in xrange(0, MAX_PORT):
		try:
			if port % 1000 == 0:
				update(port)
				
			s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
			s.settimeout(TIMEOUT)
			s.connect( (ip, port) )
			open_ports.append(port)
		except socket.error as msg:
			pass
		finally:
			s.close()
		
	return open_ports
